<template>
  <div style="width: 500px;">
    <el-input
      placeholder="请输入部门名称进行搜索..."
      prefix-icon="el-icon-search"
      v-model="filterText">
    </el-input>
    <el-tree
      :data="deps"
      :props="defaultProps"
      :filter-node-method="filterNode"
      :expand-on-click-node="false"
      ref="tree">
      <span class="custom-tree-node" slot-scope="{ node, data }" 
            style="display: flex; justify-content: space-between; width: 100%">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            type="primary"
            size="mini"
            class="depBtn"
            @click="() => showAddDep(data)">
            添加部门
          </el-button>
          <el-button
            type="danger"
            size="mini"
            class="depBtn"
            @click="() => deleteDep(data)">
            删除部门
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog
      title="添加部门"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose">
      <div>
        <table>
          <tr>
            <td><el-tag>上级部门</el-tag></td>
            <td>{{preDep}}</td>
          </tr>
          <tr>
            <td><el-tag>部门名称</el-tag></td>
            <td><el-input v-model="addDep.name" placeholder="请输入部门名称..."></el-input></td>
          </tr>
        </table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAddDep">取 消</el-button>
        <el-button type="primary" @click="doAddDep">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'DepMana',
    data() {
      return {
        filterText: '', //输入框的值
        deps: [], //接口返回的数据，用于展示
        defaultProps: { //节点树中子节点的字段配置
          children: 'children',
          label: 'name'
        },
        dialogVisible: false, //弹出框是否可见
        addDep: { //添加的部门对象
          name: '',
          parentId: ''
        },
        preDep: '' //添加时的上级部门名称
      }
    },
    watch: {
      filterText(val) { 
        // 通过监听输入框的改变，触发节点树的展示
        this.$refs.tree.filter(val);
      }
    },
    methods: {
      // 初始化部门菜单
      initDeps(){
        this.getRequest('/system/basic/department/').then(resp=>{
          if(resp){
            this.deps = resp.obj;
          }
        })
      },
      // 用于搜索过滤节点
      filterNode(value, data) {
        // val->value：搜索值  data->返回的搜索结果
        // 函数返回TRUE展示全部数据，否则展示搜索结果
        if (!value) return true; 
        return data.name.indexOf(value) !== -1;
      },
      showAddDep(data){
        this.preDep = data.name;
        this.addDep.parentId = data.id;
        this.dialogVisible = true;
      },
      // 添加部门
      doAddDep(){
        this.postRequest('/system/basic/department/', this.addDep).then(resp=>{
          if(resp){
            // 因为刷新整个页面会关闭部门树，所以这里手动添加到界面
            this.addDep2Deps(this.deps, resp.obj);
            this.dialogVisible = false;
            this.initAddDep()
          }
        })
      },
      // 初始化添加部门输入框
      initAddDep(){
        this.addDep = {
          name: '',
          parentId: -1
        }
        this.preDep = ''
      },
      // 手动添加新部门进部门树
      addDep2Deps(deps, dep){
        for(let i = 0; i < deps.length; i++){
          let d = deps[i];
          if(d.id == dep.parentId){
            d.children = d.children.concat(dep);
            // 修改isParent
            if(d.children.length > 0){
              d.isParent = true;
            }
            return;
          }else{
            this.addDep2Deps(d.children, dep);
          }
        }
      },
      cancelAddDep(){
        this.dialogVisible = false;
        this.initAddDep();
      },
      // 删除部门
      deleteDep(data){
        if(data.isParent){
          this.$message.error('父部门删除失败！')
        }else{
          this.$confirm('此操作将永久删除[ '+data.name+' ]该部门，是否继续？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.deleteRequest('/system/basic/department/'+data.id).then(resp=>{
              if(resp){
                // 手动删除列表节点
                this.removeDepFromDeps(null, this.deps, data.id)
              }
            })
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });          
          });
        }
      },
      removeDepFromDeps(p, deps, id){
        for(let i = 0; i < deps.length; i++){
          let d = deps[i];
          if(d.id == id){
            deps.splice(i, 1);
            if(deps.length==0){
              p.isParent = false;
            }
            return;
          }else{
            this.removeDepFromDeps(d, d.children, id)
          }
        }
      }
    },
    // 模板渲染完成后初始化菜单
    mounted(){
      this.initDeps();
    }
  }
</script>

<style scoped>
  .depBtn{
    padding: 2px;
  }
</style>